package org.kenewstar.user.controller;

import org.kenewstar.common.bean.pojo.MicroUser;
import org.kenewstar.common.constant.CommonConstant;
import org.kenewstar.common.utils.AssertUtil;
import org.kenewstar.common.utils.CommonResult;
import org.kenewstar.common.utils.CommonUtil;
import org.kenewstar.user.thread.MailRegisterRunnable;
import org.kenewstar.user.thread.MailResetPwdRunnable;
import org.kenewstar.user.thread.MailUpdatePwdRunnable;
import org.kenewstar.user.thread.SystemThreadPool;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 邮件控制器
 * @author kenewstar
 * @version 1.0
 * @date 2021/4/15
 */
@RestController
@RequestMapping("/mail")
@CrossOrigin(value = {CommonConstant.API_HOST}, allowCredentials = "true")
@SuppressWarnings("all")
public class MailController {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送注册账号的邮件
     * @param toMail
     * @return result
     */
    @GetMapping("/send/code")
    public CommonResult sendMail(String toMail) {
        AssertUtil.notNull(toMail);
        if (!CommonUtil.validateMail(toMail)) {
            return CommonResult.failed("邮箱格式有误");
        }
        int code = CommonUtil.generateCode();
        MailRegisterRunnable mailThread = new MailRegisterRunnable(javaMailSender);
        mailThread.setToMail(toMail);
        mailThread.setCode(code);
        SystemThreadPool.submitSendMail(mailThread);
        // 将验证码设置到redis中,过期时间300s
        redisTemplate.opsForValue()
                .set(CommonUtil.getCacheKey(CommonConstant.CachePrefix.REGISTER, toMail),
                String.valueOf(code), 600, TimeUnit.SECONDS);

        return CommonResult.success();
    }

    /**
     * 发送修改密码的邮件
     * @param toMail
     * @param session
     * @return result
     */
    @GetMapping("/send/update/pwd/code")
    public CommonResult sendUpdatePwdMail(String toMail, HttpSession session) {
        AssertUtil.notNull(toMail);
        if (!CommonUtil.validateMail(toMail)) {
            return CommonResult.failed("邮箱格式有误");
        }
        // 获取用户信息
        MicroUser user = (MicroUser) session.getAttribute(CommonConstant.SESSION_USER);
        if (!Objects.equals(user.getEmail(), toMail)) {
            return CommonResult.failed("请使用系统注册邮箱修改密码");
        }
        int code = CommonUtil.generateCode();
        MailUpdatePwdRunnable updatePwdRunnable = new MailUpdatePwdRunnable(javaMailSender);
        updatePwdRunnable.setToMail(toMail);
        updatePwdRunnable.setCode(code);
        SystemThreadPool.submitSendMail(updatePwdRunnable);
        // 将验证码设置到redis中,过期时间300s
        // key : update-username
        // value : code
        redisTemplate.opsForValue()
                .set(CommonUtil.getCacheKey(CommonConstant.CachePrefix.UPDATE, user.getUsername()),
                String.valueOf(code), 600, TimeUnit.SECONDS);
        return CommonResult.success();
    }

    /**
     * 发送重置密码的邮件
     * @param email 邮箱
     * @param session session对象
     * @return result
     */
    @GetMapping("/send/reset/pwd/url")
    public CommonResult sendResetPwdMail(String email, HttpSession session) {
        AssertUtil.notNull(email);
        if (!CommonUtil.validateMail(email)) {
            return CommonResult.failed("邮箱格式有误");
        }
        // 获取缓存key
        String cacheKey = CommonUtil.getCacheKey(CommonConstant.CachePrefix.FORGET, email);
        // 防止频繁发送邮件
        if (redisTemplate.opsForValue().get(cacheKey) != null) {
            return CommonResult.failed("请勿频繁发送邮件,每次间隔为10分钟左右");
        }
        String param = CommonUtil.generateResetParam();
        // 创建邮件任务
        MailResetPwdRunnable mailThread = new MailResetPwdRunnable(javaMailSender);
        mailThread.setToMail(email);
        mailThread.setSuffixUrl(param);
        SystemThreadPool.submitSendMail(mailThread);

        // 有效期60分钟
        redisTemplate.opsForValue()
                .set(cacheKey, param, 600, TimeUnit.SECONDS);

        return CommonResult.success();
    }



}
